package com.sky.service.admin.impl;

import com.sky.dto.OrderSumDTO;
import com.sky.mapper.admin.ReportMapper;
import com.sky.service.admin.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.List;

@Service
@Slf4j
public class WorkspaceServiceImpl implements WorkspaceService {
    @Autowired
    private ReportMapper reportMapper;

    @Override
    public BusinessDataVO businessData() {
        LocalDate now = LocalDate.now();
        return businessData(now, now);
    }

    @Override
    public BusinessDataVO businessData(LocalDate begin, LocalDate end) {
        //获取当天的订单总数，有效订单数，营业额
        List<OrderSumDTO> orderSumDTOS = reportMapper.orderStatistics(begin, end.plusDays(1));
        if(CollectionUtils.isEmpty(orderSumDTOS)){
            return new BusinessDataVO();
        }
        OrderSumDTO orderSumDTO = orderSumDTOS.get(0);
        Integer completeNum = orderSumDTO.getCompleteNum();
        Double amount = orderSumDTO.getAmount();
        Integer totalNum = orderSumDTO.getTotalNum();
        //计算订单完成率————有效订单数/订单总数
        //计算平均客单价————营业额/有效订单数
        double orderCompletionRate = 0.0;
        double unitPrice = 0.0;
        if(completeNum!=0 && totalNum != 0){
            orderCompletionRate = (double) completeNum/totalNum;
            unitPrice = amount/completeNum;
        }


        //新增用户
        Integer addUser = reportMapper.userStatistics(begin, end.plusDays(1));
        BusinessDataVO dataVO = BusinessDataVO.builder()
                .newUsers(addUser)
                .turnover(amount)
                .validOrderCount(completeNum)
                .unitPrice(unitPrice)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return dataVO;
    }

    @Override
    public DishOverViewVO dishOverView() {
        return reportMapper.overViewDishOrSetmeal("dish");
    }

    @Override
    public SetmealOverViewVO setmealOverView() {
        SetmealOverViewVO setmealOverViewVO = new SetmealOverViewVO();
        DishOverViewVO setmeal = reportMapper.overViewDishOrSetmeal("setmeal");
        BeanUtils.copyProperties(setmeal,setmealOverViewVO);
        return setmealOverViewVO;
    }
}
